#!/usr/bin/bash


# 定义检查函数
check_file_contains() {
    local file="$1"
    local pattern="$2"
    grep -qP "$pattern" "$file"
}

# 定义文件路径
PWQUALITY_CONF="/etc/security/pwquality.conf"
PAM_PASSWORD_AUTH="/etc/pam.d/password-auth"
PAM_SYSTEM_AUTH="/etc/pam.d/system-auth"

# 检查/etc/security/pwquality.conf文件中的条件
check_pwquality_conf() {
    # 检查minlen=14
    # check_file_contains "$PWQUALITY_CONF" '^minlen(?:\s*|)=(?:\s*|)14\b' || return 1
    minlenValue=$(grep -P "^\s*minlen\s*=.*" /etc/security/pwquality.conf | cut -d= -f2 | tr -d '[:space:]')
    [[ -n $minlenValue ]] && [[ $minlenValue =~ ^[0-9]+$ ]] && [[ $minlenValue -ge 14 ]] || return 1

    # 检查minclass=4 或者所有credit设置为-1
    (check_file_contains "$PWQUALITY_CONF" '^minclass(?:\s*|)=(?:\s*|)4\b') || \
    (check_file_contains "$PWQUALITY_CONF" '^dcredit(?:\s*|)=(?:\s*|)-1\b' && \
     check_file_contains "$PWQUALITY_CONF" '^ucredit(?:\s*|)=(?:\s*|)-1\b' && \
     check_file_contains "$PWQUALITY_CONF" '^ocredit(?:\s*|)=(?:\s*|)-1\b' && \
     check_file_contains "$PWQUALITY_CONF" '^lcredit(?:\s*|)=(?:\s*|)-1\b') || return 1

    return 0
}

# 检查/etc/pam.d/password-auth和/etc/pam.d/system-auth文件中的条件
check_pam_files() {
    local files=("$PAM_PASSWORD_AUTH" "$PAM_SYSTEM_AUTH")
    local patterns=("\benforce-for-root\b" "\bretry=[1-3]+\s*")

    for file in "${files[@]}"; do
        for pattern in "${patterns[@]}"; do
            check_file_contains "$file" "$pattern" || return 1
        done
    done

    return 0
}

# 执行检查
if check_pwquality_conf && check_pam_files; then
    echo "pass"
else
    echo "fail"
fi